import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_address/punch_rule_location_model.dart';
import 'package:e_reception_flutter/utils/address_about_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart' as MapImport;

class PunchRuleLocationPage extends StatefulWidget {
  final LatLng latLng;

  PunchRuleLocationPage({Key key, this.latLng}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return PunchRuleLocationState();
  }
}

class PunchRuleLocationState extends BaseState<PunchRuleLocationPage> {
  double aroundListCellH = 60;
  int maxAroundListCount = 6;
  ScrollController _scrollController = ScrollController();
  TextEditingController _searchController = TextEditingController();

  FocusNode _focusNode = FocusNode();

  /// 是否在搜索
  bool _isEditing = false;

  /// 设置mapView的key
  Key _mapKey;
  int _mapKeyIndex = 0;

  List<PunchRuleLocationSelectModel> locations = [];
  List<PunchRuleLocationModel> searchList = [];
  bool _canSave = false;
  bool _showClearImg = false;
  bool _showSearchList = false;
  LatLng loc;
  LatLng userLatLng;

  /// 搜索关键字
  String _searchKey;

  PunchRuleLocationState({this.loc});

  AMapController _mapController;

  @override
  void initState() {
    _getMapKey();

    ///加载高德定位插件
    AmapRepository.getInstance().init();
    _searchController.addListener(() {
      setState(() {
        _showClearImg =
            !StringUtils.isEmpty(_searchController.text) && _focusNode.hasFocus;
      });
    });
    _focusNode.addListener(() {
      setState(() {
        _isEditing = _focusNode.hasFocus;
      });
    });

    super.initState();
  }

  void initLocation() {
    if (widget.latLng != null) {
      loc = widget.latLng;
      _mapController.moveCamera(
          CameraUpdate.newLatLngZoom(
              MapImport.LatLng(loc.latitude, loc.longitude), 16),
          animated: true);
      return;
    }
    VgLocation().requestSingleLocation((map) {
      loc = LatLng(map["latitude"], map["longitude"]);
      _mapController.moveCamera(
          CameraUpdate.newLatLngZoom(
              MapImport.LatLng(loc.latitude, loc.longitude), 16),
          animated: true);
    });
  }

  void _searchMapMoveAddress(LatLng loc) {
    _mapController.moveCamera(
        CameraUpdate.newLatLngZoom(
            MapImport.LatLng(loc.latitude, loc.longitude), 18),
        animated: true);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _searchController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      body: SafeArea(
          bottom: true,
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
            child: Container(
              child: Column(
                children: <Widget>[
                  VgTopBarWidget(
                    isShowBack: true,
                    isShowGrayLine: false,
                    title: "GPS位置",
                    titleColor: Color(0xff333333),
                    rightPadding: 15,
                    rightWidget: ClickAnimateWidget(
                        scale: 1.1,
                        onClick: () {
                          if (!_canSave) {
                            return;
                          }
                          PunchRuleLocationSelectModel model;
                          locations.forEach((element) {
                            if (element.isSelect) {
                              model = element;
                            }
                          });
                          Map<String,dynamic> maps = Map();
                          maps["llat"] = AddressAboutUtils.getLongitudeAndLatitude(
                              model?.long?.toString(), model?.lat?.toString());
                          maps["title"] = model?.title;
                          maps["adCode"] = model?.adCode;
                          maps["province"] = model?.province;
                          maps["city"] = model?.city;
                          maps["district"] = model?.district;

                          if (model != null) {
                            RouterUtils.pop(context, result: maps);
                          }
                        },
                        child: Container(
                          alignment: Alignment.center,
                          padding:
                              EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(12)),
                            color: _canSave
                                ? Color(0xFF00C6C4)
                                : Color(0xFFCFD4DB),
                          ),
                          child: Text(
                            "确定",
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(0xFFFFFFFF),
                            ),
                          ),
                        )),
                  ),
                  _getSearchView(),
                  Expanded(
                    child: Stack(
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            Expanded(
                              child: Stack(
                                children: [
                                  AMapWidget(
                                    // onLocationChanged: (val) async {
                                    //
                                    // },
                                    mapType: MapType.normal,
                                    onMapCreated: (controller) async {
                                      _mapController = controller;
                                      if (_mapController != null) {
                                        initLocation();
                                      }
                                    },
                                    onCameraMoveEnd: (details) async {
                                      LatLng latlng = LatLng(
                                          details.target.latitude,
                                          details.target.longitude);
                                      // LatLng latlng = LatLng(loc.latitude, loc.longitude);
                                      List<Poi> reGeocode = await AmapSearch
                                          .instance
                                          .searchAround(latlng);
                                      _getAroundLocation(reGeocode);
                                    },
                                    myLocationStyleOptions:
                                    MyLocationStyleOptions(
                                        true,
                                        circleFillColor: Colors.transparent,
                                        circleStrokeColor:
                                        Colors.transparent),
                                    // onPoiTouched: (details) {
                                    //   print(details.name);
                                    // },

                                    // markers: _markerList,
                                    scaleEnabled: true,
                                  ),
                                  _alternativeAddRess(),
                                  _myPosition(),
                                ],

                              ),
                            ),
                            Align(
                              alignment: Alignment.bottomCenter,
                              child: Container(
                                padding: EdgeInsets.only(top: 10),
                                margin: EdgeInsets.symmetric(horizontal: 15),
                                height: maxAroundListCount * aroundListCellH,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(15),
                                      topRight: Radius.circular(15)),
                                  color: Color(0xFFFFFFFF),
                                ),
                                child: ScrollConfiguration(
                                  behavior: MyBehavior(),
                                  child: ListView.builder(
                                      controller: _scrollController,
                                      itemCount: locations.length,
                                      itemBuilder: (context, index) {
                                        return ClickAnimateWidget(
                                          child: _getLocationItem(index,
                                              locations.length - 1 == index),
                                          onClick: () {
                                            PunchRuleLocationSelectModel model =
                                                locations[index];
                                            setState(() {
                                              locations.forEach((element) {
                                                if (element.isSelect) {
                                                  element.isSelect =
                                                      !element.isSelect;
                                                }
                                              });
                                              model.isSelect = !model.isSelect;
                                              loc =
                                                  LatLng(model.lat, model.long);
                                              _searchMapMoveAddress(loc);
                                            });
                                          },
                                        );
                                      }),
                                ),
                              ),
                            )
                          ],
                        ),
                        Visibility(
                            visible: _isEditing,
                            child: Positioned(
                              left: 0,
                              right: 0,
                              top: 0,
                              bottom: 0,
                              child: Container(
                                color: Colors.black.withOpacity(.4),
                              ),
                            )),
                        Visibility(
                            visible: _showSearchList,
                            child: Positioned(
                              top: 0,
                              left: 0,
                              bottom: 0,
                              right: 0,
                              child: Container(
                                color: Colors.white,
                                child: ListView.builder(
                                    itemCount: searchList == null
                                        ? 0
                                        : searchList.length,
                                    itemBuilder: (context, index) {
                                      return _getSearchLocationItem(index,
                                          searchList.length - 1 == index);
                                    }),
                              ),
                            )),

                      ],
                    ),
                  ),
                ],
              ),
            ),
          )),
    );
  }
  //备选位置
  Widget _alternativeAddRess(){
    return Positioned(
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        child: Center(
          child: GestureDetector(
            onTap: () {
              SystemChannels.textInput
                  .invokeMethod('TextInput.hide');
            },
            child: Container(
              alignment: Alignment.center,
              child: Container(
                width: 20,
                height: 60,
                child: Image.asset(
                  "images/location.png",
                  width: 20,
                  height: 62,
                ),
              ),
            ),
          ),
        ));
  }

  //我的位置
  Widget _myPosition(){
    return Positioned(
        right: 15,
        bottom: 15,
        child: Center(
            child: GestureDetector(
          child: Container(
            width: 40,
            height: 40,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(4)),
                boxShadow: [
                  BoxShadow(
                      color: Color.fromRGBO(0, 0, 0, 0.1),
                      offset: Offset(0, 0),
                      blurRadius: 10)
                ]),
            child: Image.asset("images/dingwei.png", width: 22, height: 22),
          ),
          behavior: HitTestBehavior.translucent,
          onTap: () {
            _searchMapMoveAddress(widget?.latLng);
          },
        )));
  }

  /// 搜索位置
  Widget _getSearchLocationItem(int index, bool isLast) {
    PunchRuleLocationModel model = searchList[index];
    return ClickAnimateWidget(
      child: Container(
        child: Column(
          children: <Widget>[
            Container(
                padding: EdgeInsets.symmetric(horizontal: 15, vertical: 7),
                child: Column(
                  children: <Widget>[
                    Container(
                      height: 21,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        model.title,
                        style: TextStyle(
                          fontSize: 15,
                          color: Color(0xFF333333),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Container(
                      height: 16,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        model.detail,
                        style: TextStyle(
                          fontSize: 11,
                          color: Color(0xFF999999),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    )
                  ],
                )),
            Visibility(
              visible: !isLast,
              child: Container(
                margin: EdgeInsets.only(left: 12),
                height: 0.5,
                color: Color(0xFFE5E5E5),
              ),
            )
          ],
        ),
      ),
      onClick: () {
        FocusScope.of(context).requestFocus(FocusNode());
        setState(() {
          loc = LatLng(model.lat, model.long);
          _searchMapMoveAddress(loc);
          _showSearchList = false;
          _getMapKey();
        });
      },
    );
  }

  /// 定位周边位置
  Widget _getLocationItem(int index, bool isLast) {
    PunchRuleLocationSelectModel model = locations[index];
    return Column(
      children: <Widget>[
        Container(
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 10),
                      height: 21,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        model.extendTitle,
                        style: TextStyle(
                          fontSize: 15,
                          color: Color(0xFF333333),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 2, bottom: 10),
                      height: 16,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        model.detail,
                        style: TextStyle(
                          fontSize: 11,
                          color: Color(0xFF9C9FA1),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    )
                  ],
                ),
              ),
              Container(
                  margin: EdgeInsets.only(left: 45),
                  child: Visibility(
                    visible: model.isSelect,
                    child: Image.asset(
                      "images/duigou_ico.png",
                      width: 14,
                      height: 9,
                    ),
                  )),
            ],
          ),
        ),
        Visibility(
          visible: !isLast,
          child: Container(
            margin: EdgeInsets.only(left: 15),
            height: 0.5,
            color: Color(0xFFEEEEEE),
          ),
        )
      ],
    );
  }

  /// 搜索栏
  Widget _getSearchView() {
    return Container(
      alignment: Alignment.center,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 15),
      height: 50,
      child: Container(
        alignment: Alignment.center,
        height: 30,
        decoration: BoxDecoration(
            color: Color(0xFFF2F2F2), borderRadius: BorderRadius.circular(15)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(left: 12),
              child: Image.asset(
                "images/sousuo_ico.png",
                width: 16,
                height: 16,
              ),
            ),
            Container(width: 5),
            Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: TextField(
                  focusNode: _focusNode,
                  onSubmitted: (content) async {},
                  textInputAction: TextInputAction.search,
                  textAlign: TextAlign.start,
                  maxLines: 1,
                  onChanged: (content) {
                    if (StringUtils.isEmpty(content)) {
                      setState(() {
                        searchList.clear();
                      });
                    } else {
                      if (content != _searchKey) {
                        searchList.clear();
                        _searchKey = content;
                      }

                      AmapSearch.instance.searchKeyword(content).then((value) {
                        _getSearchLocation(value);
                      });
                    }
                  },
                  controller: _searchController,
                  style: TextStyle(
                    fontSize: 13,
                    color: Color(0xFF333333),
                  ),
                  decoration: InputDecoration(
                    hintText: '搜索地点',
                    border: InputBorder.none,
                    counterText: '',
                    hintStyle: TextStyle(
                      fontSize: 13,
                      color: Color(0xFFBBBBBB),
                    ),
                  ),
                ),
              ),
            ),
            _showClearImg
                ? GestureDetector(
                    onTap: () {
                      setState(() {
                        _searchController.text = "";
                        _showClearImg = false;
                        searchList.clear();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.only(right: 15, left: 5),
                      child: Image.asset(
                        "images/delete_grey_ico.png",
                        width: 16,
                        height: 16,
                      ),
                    ))
                : Container()
          ],
        ),
      ),
    );
  }

  _getSearchLocation(List<Poi> maps) async {
    if (maps != null) {
      for (Poi item in maps) {
        LatLng latLng = await item.latLng;
        String adCode = await item.adCode;
        String province = await item.provinceName;
        String city = await item.cityName;
        String district = await item.adName;
        PunchRuleLocationModel model = PunchRuleLocationModel(
            await item.title, await item.title, await item.address,adCode,province,city,district,
            lat: latLng.latitude, long: latLng.longitude);
        searchList.add(model);
      }
    }
    setState(() {
      _showSearchList = searchList.length > 0;
    });
  }

  _getAroundLocation(List<Poi> poiList) async {
    if (locations.length > 0) {
      locations.clear();
    }
    List<Poi> maps = await poiList;
    if (maps != null) {
      for (int i = 0; i < maps.length; i++) {
        Poi item = maps[i];
        LatLng latlng = await item.latLng;
        bool isSelect = i == 0;
        String title = await item.title;
        String adCode = await item.adCode;
        String province = await item.provinceName;
        String city = await item.cityName;
        String district = await item.adName;
        PunchRuleLocationSelectModel model = PunchRuleLocationSelectModel(
            await item.title, title, await item.address, adCode,province,city,district,isSelect,
            lat: latlng.latitude, long: latlng.longitude);
        locations.add(model);
      }
    }
    _scrollController.jumpTo(0);
    setState(() {
      _canSave = locations.length > 0;
    });
  }

  _getMapKey() {
    _mapKeyIndex += 1;
    _mapKey = Key("$_mapKeyIndex");
  }
}
